<?php

namespace app\admin\controller\system;

use app\admin\controller\AuthController;
use app\model\system\SystemAdmin;
use app\model\system\SystemRole;
use albert\services\FormBuilder;
use albert\services\JsonService;
use albert\services\UtilService;
use FormBuilder\exception\FormBuilderException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 管理员控制器
 * Class AdminController
 * @package app\admin\controller\system
 */
class AdminController extends AuthController
{
    /**
     * 列表展示页
     * Author: Albert3306
     * Date: 2021/5/6
     * @return string
     */
    public function index(): string
    {
        return $this->fetch('system/admin');
    }

    /**
     * 列表数据
     * Author: Albert3306
     * Date: 2021/5/6
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function lst(): string
    {
        $admin = $this->admin;
        $params = UtilService::param([
            ['page', 0],
            ['limit', 20],
            ['status', ''],
            ['keywords', ''],
            ['level', bcadd($admin->level, 1, 0)],
        ]);
        $data = SystemAdmin::getLayUIPageList($params);
        return JsonService::successLayUI($data['count'], $data['data']);
    }

    /**
     * 添加展示页
     * Author: Albert3306
     * Date: 2021/5/7
     * @return string
     * @throws FormBuilderException
     */
    public function create(): string
    {
        $f = [];
        $admin = $this->admin;
        $f[] = FormBuilder::input('username', '账号');
        $f[] = FormBuilder::input('pwd', '密码')->type('password');
        $f[] = FormBuilder::input('conf_pwd', '确认密码')->type('password');
        $f[] = FormBuilder::input('nickname', '昵称');
        $f[] = FormBuilder::select('roles', '角色')->setOptions(function () use ($admin) {
            $list = SystemRole::getRole(bcadd($admin->level, 1, 0));
            $options = [];
            foreach ($list as $id => $roleName) {
                $options[] = ['label' => $roleName, 'value' => $id];
            }
            return $options;
        })->multiple(1);
        $f[] = FormBuilder::radio('status', '状态', 1)->options([['label' => '开启', 'value' => 1], ['label' => '关闭', 'value' => 0]]);
        $form = FormBuilder::make_post_form('添加管理员', $f, '/admin/system/user/save');
        return $this->fetch('public/form-builder', [
            'form' => $form
        ]);
    }

    /**
     * 添加保存
     * Author: Albert3306
     * Date: 2021/5/7
     * @return string
     */
    public function save(): string
    {
        $data = UtilService::param([
            'username',
            'conf_pwd',
            'pwd',
            'nickname',
            ['roles', []],
            ['status', 0]
        ]);
        if (!$data['username']) return JsonService::fail('请输入管理员账号！');
        if (!$data['roles']) return JsonService::fail('请选择至少一个管理员身份！');
        if (!$data['pwd']) return JsonService::fail('请输入管理员登陆密码！');
        if ($data['pwd'] != $data['conf_pwd']) return JsonService::fail('两次输入密码不想同！');
        if (SystemAdmin::be($data['username'], 'username')) return JsonService::fail('管理员账号已存在！');
        $data['reg_at'] = date('Y-m-d H:i:s');
        $data['reg_ip'] = app('request')->ip();
        $data['pwd'] = password_hash($data['pwd'], PASSWORD_DEFAULT, ['cost' => 11]);
        unset($data['conf_pwd']);
        $data['level'] = $this->admin['level'] + 1;
        if (!SystemAdmin::create($data)) return JsonService::fail('添加管理员失败！');
        return JsonService::successful('添加管理员成功！');
    }

    /**
     * 编辑展示页
     * Author: Albert3306
     * Date: 2021/5/7
     * @param $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     */
    public function edit($id): string
    {
        if (!$id) return $this->failed('参数错误！');
        $admin = SystemAdmin::get($id);
        if (!$admin) return $this->failed('数据不存在！');
        $f = array();
        $f[] = FormBuilder::input('username', '账号', $admin->username);
        $f[] = FormBuilder::input('pwd', '密码')->type('password');
        $f[] = FormBuilder::input('conf_pwd', '确认密码')->type('password');
        $f[] = FormBuilder::input('nickname', '昵称', $admin->nickname);
        $f[] = FormBuilder::select('roles', '角色', explode(',', $admin->roles))->setOptions(function () use ($admin) {
            $list = SystemRole::getRole($admin->level);
            $options = [];
            foreach ($list as $id => $roleName) {
                $options[] = ['label' => $roleName, 'value' => $id];
            }
            return $options;
        })->multiple(1);
        $f[] = FormBuilder::radio('status', '状态', $admin->status)->options([['label' => '开启', 'value' => 1], ['label' => '关闭', 'value' => 0]]);
        $form = FormBuilder::make_post_form('编辑管理员', $f, '/admin/system/user/update/' . $id);
        return $this->fetch('public/form-builder', [
            'form' => $form
        ]);
    }

    /**
     * 编辑保存
     * Author: Albert3306
     * Date: 2021/5/7
     * @param $id
     * @return string
     */
    public function update($id): string
    {
        $data = UtilService::param([
            'username',
            'conf_pwd',
            'pwd',
            'nickname',
            ['roles', []],
            ['status', 0]
        ]);
        if (!$data['username']) return JsonService::fail('请输入管理员账号！');
        if (!$data['roles']) return JsonService::fail('请选择至少一个管理员身份！');
        if (!$data['pwd'])
            unset($data['pwd']);
        else {
            if (isset($data['pwd']) && $data['pwd'] != $data['conf_pwd']) return JsonService::fail('两次输入密码不想同！');
            $data['pwd'] = md5($data['pwd']);
        }
        if (SystemAdmin::where('username', $data['username'])->where('id', '<>', $id)->count()) return JsonService::fail('管理员账号已存在！');
        unset($data['conf_pwd']);
        if (!SystemAdmin::edit($data, $id)) return JsonService::fail('修改失败！');
        return JsonService::successful('修改成功！');
    }

    /**
     * 逻辑删除
     * Author: Albert3306
     * Date: 2021/5/7
     * @param $id
     * @return string
     */
    public function delete($id): string
    {
        if (!$id)
            return JsonService::fail('删除失败！');
        if (SystemAdmin::edit(['is_del' => 1, 'status' => 0], $id, 'id'))
            return JsonService::successful('删除成功！');
        else
            return JsonService::fail('删除失败！');
    }

    /**
     * 设置状态
     * Author: Albert3306
     * Date: 2021/5/7
     * @param $status
     * @param $id
     * @return string
     */
    public function setStatus($status, $id): string
    {
        if (SystemAdmin::edit(['status' => $status], $id)) return JsonService::success('设置成功！');
        return JsonService::fail('设置失败！');
    }

    /**
     * 个人资料
     * Author: Albert3306
     * Date: 2021/7/6
     * @return string
     */
    public function info(): string
    {
        $f = [];
        $admin = $this->admin;
        $f[] = FormBuilder::input('username', '账号', $admin['username'])->disabled(true);
        $f[] = FormBuilder::input('nickname', '昵称', $admin['nickname']);
        $f[] = FormBuilder::input('old_pwd', '原始密码')->type('password');
        $f[] = FormBuilder::input('new_pwd', '新密码')->type('password');
        $f[] = FormBuilder::input('cfm_pwd', '确认密码')->type('password');
        $form = FormBuilder::make_post_form('编辑管理员', $f, '/admin/system/save_info');
        return $this->fetch('public/form-builder', [
            'form' => $form
        ]);
    }

    /**
     * 个人资料保存
     * Author: Albert3306
     * Date: 2021/7/6
     * @return string
     */
    public function saveInfo(): string
    {
        $aid = $this->aid;
        $data = UtilService::param([
            ['old_pwd', ''],
            ['new_pwd', ''],
            ['cfm_pwd', ''],
            ['nickname', ''],
        ], $this->request);
        if ($data['old_pwd'] != '') {
            if (!password_verify($data['old_pwd'], SystemAdmin::initWhere(['id' => $aid])->value('pwd'))) return JsonService::fail('原始密码错误！');
        }
        if ($data['new_pwd'] != '') {
            if (!$data['cfm_pwd']) return JsonService::fail('请输入确认密码！');
            if ($data['new_pwd'] != $data['cfm_pwd']) return JsonService::fail('两次密码不一致！');
        }
        if ($data['old_pwd'] != '' && $data['new_pwd'] != '') {
            $data['pwd'] = password_hash($data['new_pwd'], PASSWORD_DEFAULT, ['cost' => 11]);
        }
        unset($data['old_pwd'], $data['new_pwd'], $data['cfm_pwd']);
        if (SystemAdmin::edit($data, $aid)) return JsonService::success('修改成功，请重新登录！');
        return JsonService::fail('修改失败！');
    }
}